import { reactive } from 'vue'
import { useForm } from 'ant-design-vue/es/form'
import { useHttpRequest } from '@/api/chunfeng/apiRequest'
import { NewExpenseParam } from '@/api/chunfeng/finance/expense/interfaces'
import moment from 'moment'
import { useExpenseApi } from '@/api/chunfeng/finance/expense'

export const useExpenseAddFunctions = () => {
  const newParam = reactive<NewExpenseParam>({
    name: '',
    expenseTypeId: '',
    amount: 0,
    remark: undefined,
    occurredAt: moment().format('yyyy-MM-DD'),
  })
  const rules = reactive({
    name: [
      {
        required: true,
        message: '请输入名称',
      },
    ],
    expenseTypeId: [
      {
        required: true,
        message: '请选择费用类型',
      },
    ],
    amount: [
      {
        required: true,
        message: '请输入就金额',
      },
    ],
    occurredAt: [
      {
        required: true,
        message: '请选择发生日期',
      },
    ],
    remark: [
      {
        required: false,
      },
    ],
  })

  const { validateInfos, resetFields, validate } = useForm(newParam, rules)
  const { executeCommandRequest } = useHttpRequest()
  const { newExpense } = useExpenseApi()

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  }

  function addExpense() {
    validate().then((data: NewExpenseParam) => {
      executeCommandRequest(newExpense(data), {
        message: '新增费用成功',
        callback: () => {
          resetFields()
        },
      })
    })
  }

  function reset() {
    resetFields()
  }

  function expenseTypeSelected(expenseTypeId: string) {
    newParam.expenseTypeId = expenseTypeId
  }

  return {
    newParam,
    validateInfos,
    addExpense,
    reset,
    layout,
    expenseTypeSelected,
  }
}
